package com.kittlen.managementSystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kittlen.managementSystem.entity.*;
import com.kittlen.managementSystem.service.ICoachService;
import com.kittlen.managementSystem.service.IVehicleService;
import com.kittlen.managementSystem.utils.FileUpload;
import com.kittlen.managementSystem.utils.Md5;
import com.kittlen.managementSystem.utils.ObjectUtil;
import com.kittlen.managementSystem.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ImportResource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 教练表 前端控制器
 * </p>
 *
 * @author kittlen
 * @since 2021-01-26
 */
@RestController
@ImportResource("classpath:/springmvc-servlet.xml")
@RequestMapping("/coach")
public class CoachController {

    @Resource
    ICoachService iCoachService;

    @Value("${Upload_CoachPhotoFile}")
    String coachPhotoFile;

    /**
     * 教练登陆
     *
     * @param userId
     * @param pwd
     * @return
     */
    @RequestMapping("/login")
    public Result login(String userId, String pwd, HttpServletRequest request) {
        Result result = new Result();
        Coach coach = iCoachService.getById(userId);
        if (ObjectUtil.isNoEmpty(coach)) {
            if (pwd.equals(coach.getPwd())) {
                coach.setPwd("");
                result.setData(coach);
                request.getSession().setAttribute("user", coach);
                request.getSession().setAttribute("type", 2);
                return result;
            }
        }
        result.setCode(result.RESULT_ERROR);
        result.setMsg("账号或密码错误");
        return result;
    }

    /**
     * 教练查询
     *
     * @param coach
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("selects")
    public Result selects(Coach coach, @RequestParam(required = false, defaultValue = "0") int page,
                          @RequestParam(required = false, defaultValue = "0") int limit,
                          @RequestParam(required = false, defaultValue = "0") int isFree) {
        Result result = new Result();
        QueryWrapper<Coach> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNoEmpty(coach.getCoachId())) {
            queryWrapper.like("coach_id", coach.getCoachId());
        }
        if (ObjectUtil.isNoEmpty(coach.getFullname())) {
            queryWrapper.like("fullname", coach.getFullname());
        }
        if (ObjectUtil.isNoEmpty(coach.getAgender())) {
            queryWrapper.like("agender", coach.getAgender());
        }
        if (ObjectUtil.isNoEmpty(coach.getPhone())) {
            queryWrapper.like("phone", coach.getPhone());
        }
        if (ObjectUtil.isNoEmpty(coach.getEmail())) {
            queryWrapper.like("email", coach.getEmail());
        }
        if (ObjectUtil.isNoEmpty(coach.getIsEnd())) {//是否辞职
            queryWrapper.eq("is_end", coach.getIsEnd());
        }
        if (ObjectUtil.isNoEmpty(coach.getIsStartChoice())) {//是否开始被选
            queryWrapper.eq("is_start_choice", coach.getIsStartChoice());
        }
        if (ObjectUtil.isNoEmpty(coach.getTeachingStage()) && coach.getTeachingStage() != 0) {//主要负责的教学科目
            queryWrapper.eq("teaching_stage", coach.getTeachingStage());
        }
        if (page != -1) {
            MySqlLimit mySqlLimit = new MySqlLimit(page, limit);
            queryWrapper.last("LIMIT " + mySqlLimit.getOffset() + "," + mySqlLimit.getRows());
        }
        if (ObjectUtil.isNoEmpty(isFree) && isFree != 0) {//当前未全部分派有教练
            queryWrapper.apply("choice_count < choice_count_max");
        }
        List<Coach> list = iCoachService.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setPwd("");
        }
        result.setData(list);
        queryWrapper.last("");
        result.setCount(iCoachService.count(queryWrapper));
        return result;
    }

    /**
     * 教练选择
     *
     * @param type          排序类型 1评分 2入职时间
     * @param teachingStage 教学阶段
     * @param page
     * @param limit
     * @param agender       性别
     * @param fullname      姓名
     * @param isChoice      是否是选择 (0:可选 教练为可选状态,当前学员数小数总学员数;1:排名状态)
     * @return
     */
    @RequestMapping("selectByEvaluate")
    public Result selects(@RequestParam(required = false, defaultValue = "0") int type, @RequestParam(required = false, defaultValue = "0") int teachingStage, @RequestParam(required = false, defaultValue = "0") int page,
                          @RequestParam(required = false, defaultValue = "0") int limit, @RequestParam(required = false, defaultValue = "-1") int agender, @RequestParam(required = false, defaultValue = "") String fullname,
                          @RequestParam(required = false, defaultValue = "0") int isChoice) {
        Result result = new Result();
        QueryWrapper<Coach> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_end", "0");//未离职
        if (isChoice == 0) {
            queryWrapper.eq("is_start_choice", "1");//开始被选
            queryWrapper.apply("choice_count < choice_count_max");//未被选满
        }
        if (ObjectUtil.isNoEmpty(teachingStage) && teachingStage != 0) {//主要负责的教学科目
            queryWrapper.eq("teaching_stage", teachingStage);
        }
        if (agender != -1) {//性别
            queryWrapper.eq("agender", agender);
        }
        if (ObjectUtil.isNoEmpty(fullname)) {//姓名
            queryWrapper.like("fullname", fullname);
        }
        if (type == 1) {
            queryWrapper.orderByDesc("score");
        } else if (type == 2) {
            queryWrapper.isNotNull("joining_time");
            queryWrapper.orderByAsc("joining_time");
        }
        if (page != -1) {
            MySqlLimit mySqlLimit = new MySqlLimit(page, limit);
            queryWrapper.last("LIMIT " + mySqlLimit.getOffset() + "," + mySqlLimit.getRows());
        } else {
            queryWrapper.last("LIMIT 0,3");

        }
        List<Coach> list = iCoachService.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setPwd("");
        }
        result.setData(list);
        queryWrapper.last("");
        result.setCount(iCoachService.count(queryWrapper));
        return result;
    }

    /**
     * 教练添加
     *
     * @param coach
     * @return
     */
    @RequestMapping("/insert")
    public Result insert(Coach coach) throws NoSuchAlgorithmException {
        Result result = new Result();
        if (!ObjectUtil.isNoEmpty(coach.getJoiningTime())) {
            coach.setJoiningTime(TimeUtil.getNowTime());
        }
        coach.setPwd(Md5.UseMD5("123456"));
        try {
            if (iCoachService.save(coach)) {
                result.setData(coach);
                result.setMsg("教练添加成功");
            } else {
                result.setCode(result.RESULT_ERROR);
                result.setMsg("教练添加失败");
            }
        } catch (DuplicateKeyException e) {
            result.setCode(result.RESULT_ERROR);
            result.setMsg("教练添加失败,教练ID重复了");
        }

        return result;
    }

    /**
     * 教练添加
     *
     * @param coachsStr
     * @return
     */
    @RequestMapping("/coachImport")
    public Result coachImport(String coachsStr) {
        Result result = new Result();
        List<Coach> list = new Gson().fromJson(coachsStr, new TypeToken<List<Coach>>() {
        }.getType());
        try {
            if (iCoachService.saveBatch(list)) {
                result.setMsg("教练添加成功");
            } else {
                result.setCode(result.RESULT_ERROR);
                result.setMsg("教练添加失败");
            }
        } catch (DuplicateKeyException e) {
            String err=e.getCause().toString();
            String errID=err.substring(err.indexOf("Duplicate entry")+15,err.indexOf("for key"));
            result.setCode(result.RESULT_ERROR);
            result.setMsg("教练添加失败,教练ID"+errID+"重复了");
        }

        return result;
    }

    /**
     * 修改密码
     *
     * @param
     * @return
     */
    @RequestMapping("/updatePwd")
    public Result updatePwd(String coachId, @RequestParam(required = false, defaultValue = "") String newPwd, @RequestParam(required = false, defaultValue = "") String oldPwd) {
        Result result = new Result();
        if (ObjectUtil.isNoEmpty(newPwd) && ObjectUtil.isNoEmpty(oldPwd)) {
            Coach coach = iCoachService.getById(coachId);
            if (ObjectUtil.isNoEmpty(coach)) {
                if (coach.getPwd().equals(oldPwd)) {
                    iCoachService.update(new UpdateWrapper<Coach>().set("pwd", newPwd).eq("coach_id", coachId));
                    result.setMsg("密码修改成功,请重新登陆");
                } else {
                    result.setMsg("密码修改失败,原密码错误");
                    result.setCode(result.RESULT_ERROR);
                }
            } else {
                result.setMsg("账号信息异常,请重新登陆");
                result.setCode(result.RESULT_ERROR);
            }
        } else {
            try {
                Coach coach = new Coach(coachId);
                coach.setPwd(Md5.UseMD5("123456"));
                iCoachService.updateById(coach);
                result.setMsg("密码重置成功");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 教练修改
     *
     * @param coach
     * @return
     */
    @RequestMapping("/update")
    public Result update(Coach coach, String vehicleId, String vehicleOldId) throws Exception {
        Result result = new Result();
        if (ObjectUtil.isNoEmpty(vehicleId)) {
            if (vehicleId.equals(vehicleOldId)) {
                if (iCoachService.updateById(coach)) {
                    coach = iCoachService.getById(coach.getCoachId());
                    coach.setPwd("");
                    result.setData(coach);
                    result.setMsg("教练信息修改成功");
                } else {
                    result.setCode(result.RESULT_ERROR);
                    result.setMsg("教练信息修改失败");
                }
                return result;
            } else {
                if (iCoachService.updateAndVehicle(coach, vehicleId, vehicleOldId)) {
                    coach = iCoachService.getById(coach.getCoachId());
                    coach.setPwd("");
                    result.setData(coach);
                    result.setMsg("教练信息修改成功");
                } else {
                    result.setCode(result.RESULT_ERROR);
                    result.setMsg("教练信息修改失败");
                }
                return result;
            }
        } else {
            if (iCoachService.updateById(coach)) {
                coach = iCoachService.getById(coach.getCoachId());
                coach.setPwd("");
                result.setData(coach);
                result.setMsg("教练信息修改成功");
            } else {
                result.setCode(result.RESULT_ERROR);
                result.setMsg("教练信息修改失败");
            }
            return result;
        }

    }

    /**
     * 照片上传
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/photoUpdate")
    public Result photoUpdate(MultipartFile file, HttpServletRequest request) {
        Result result = new Result();
        if (file.isEmpty()) {
            result.setMsg("文件上传异常");
            result.setCode(result.RESULT_ERROR);
        } else {
            Object object = SessionController.getSession(request, "user");
            if (object == null) {
                result.setCode(Result.RESULT_ERROR);
                result.setMsg("用户信息错误,请重新登陆");
                return result;
            }
            Coach coach = (Coach) object;
            Map<String, String> map = FileUpload.upload(file, coachPhotoFile + coach.getCoachId() + "/", request);
            if (ObjectUtil.isNoEmpty(map.get("fileRelativePath"))) {
                iCoachService.update(new UpdateWrapper<Coach>().eq("coach_id", coach.getCoachId()).set("photo", map.get("fileRelativePath")));
                coach.setPhoto(map.get("fileRelativePath"));
                request.getSession().setAttribute("user",coach);
                result.setData(coach);
                result.setMsg("上传成功");
            } else {
                result.setCode(result.RESULT_ERROR);
                result.setMsg("上传失败");

            }
        }
        return result;
    }

    /**
     * 教练修改
     *
     * @param
     * @return
     */
    @RequestMapping("/updates")
    public Result updates(String coachsStr, @RequestParam(required = false, defaultValue = "0") int teachingStage, @RequestParam(required = false, defaultValue = "-1") int isStartChoice) {
        Result result = new Result();
        Coach.Coachs coachs = new Gson().fromJson(coachsStr, Coach.Coachs.class);
        if (teachingStage != 0) {
            iCoachService.update(new UpdateWrapper<Coach>().in("coach_id", coachs.getCoachIds()).set("teaching_stage", teachingStage));
            result.setMsg("教学阶段修改成功");
        }
        if (isStartChoice != -1) {
            iCoachService.update(new UpdateWrapper<Coach>().in("coach_id", coachs.getCoachIds()).set("is_start_choice", isStartChoice == 0 ? false : true));
            result.setMsg("被选状态修改成功");
        }
        return result;
    }

    /**
     * 修改全部教练的选择状态
     *
     * @param
     * @return
     */
    @RequestMapping("/updateAllIsStartChoice")
    public Result updateAllIsStartChoice(@RequestParam(required = false, defaultValue = "0") int teachingStage, @RequestParam(required = false, defaultValue = "-1") int isStartChoice) {
        Result result = new Result();
        if (teachingStage != 0&&isStartChoice!=-1) {
            iCoachService.update(new UpdateWrapper<Coach>().eq("teaching_stage", teachingStage).set("is_start_choice", isStartChoice));
            result.setMsg("修改教练选择状态成功");
        }
        return result;
    }

    /**
     * 教练删除
     *
     * @param coach
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Coach coach) {
        Result result = new Result();
        try {
            if (iCoachService.removeById(coach)) {
                result.setMsg("删除成功");
            } else {
                result.setMsg("删除失败");
                result.setCode(result.RESULT_ERROR);
            }
        } catch (Exception e) {
            result.setMsg("该教练已经与其他教练或车辆绑定,无法进行删除");
            result.setCode(result.RESULT_ERROR);
        } finally {
            return result;
        }
    }

    @RequestMapping("/selectById")
    public Result selectById(String coachId){
      Coach coach=iCoachService.getById(coachId);
      coach.setPwd("");
      return new Result(coach,"查询成功");
    };

}
